<template>
  <div class="mobile-view-wrapper">
    <div class="mobile-view">
      <el-scrollbar>
        <van-cell-group inset style="margin: 0">
          <div
            class="mobile-view-item"
            v-for="(obj, i) in arr"
            :key="obj.id"
            draggable="true"
            @dragstart="dragStart($event, i)"
            @dragover="dragOver($event, i)"
            @drop="drop($event, i)"
            @dragend="dragEnd($event, i)"
          >
            <i class="icon iconfont">&#xe647;</i>
            <FormItem :tdId="obj.tdId" type="config-mobile" />
          </div>
        </van-cell-group>
      </el-scrollbar>
    </div>
  </div>
</template>

<script setup lang="ts">
const { forms, updateForm } = inject<{ forms: any; updateForm: (forms: any) => void }>('forms', {
  forms: [],
  updateForm: () => {}
})
const arr = ref<
  {
    id: string
    tdId: string
  }[]
>([])
const dragIndex = ref<number | null>(null)
const hoverIndex = ref<number | null>(null)
const dragStart = (e: DragEvent, index: number) => {
  // console.log('dragStart', e, index)
  dragIndex.value = index
}
const dragOver = (e: DragEvent, index: number) => {
  e.preventDefault()
  // console.log('dragOver', e, index, dragIndex.value)
  hoverIndex.value = index
  if (dragIndex.value != null && dragIndex.value != index) {
    const move = arr.value[dragIndex.value]
    arr.value.splice(dragIndex.value, 1)
    arr.value.splice(index, 0, move)
    dragIndex.value = index
    arr.value = [...arr.value]
  }
}
const drop = (e: DragEvent, index: number) => {
  e.preventDefault()
  // console.log('drop', e, index, dragIndex.value)
  if (dragIndex.value != null && dragIndex.value != index) {
    const move = arr.value[dragIndex.value]
    arr.value.splice(dragIndex.value, 1)
    arr.value.splice(index, 0, move)
    dragIndex.value = index
    arr.value = [...arr.value]
  }
}
const dragEnd = (e: DragEvent, index: number) => {
  // console.log('dragEnd', e, index)
  // 这里可以添加拖拽结束后的处理逻辑，比如更新后端数据等
  updateForm(arr.value)
}
watch(forms, () => {
  arr.value = forms.value.filter((el) => {
    return el.formType != 'RemarkText'
  })
})
onMounted(() => {
  arr.value = forms.value.filter((el) => {
    return el.formType != 'RemarkText'
  })
})
</script>

<style lang="scss">
.mobile-view-wrapper {
  padding: 50px 0;
  display: flex;
  justify-content: center;
  .mobile-view {
    width: 375px;
    height: 667px;
    box-shadow: 0 0 10px 1px rgba(0, 0, 0, 0.1);
    .mobile-view-item {
      display: flex;
      align-items: center;
      border-bottom: 1px solid #eeeeee;
      .icon {
        padding-left: 10px;
        cursor: move;
      }
    }
  }
}
</style>
